// https://leetcode.cn/problems/exclusive-time-of-functions/
// Created by ade on 2022/8/12.
//
#include <iostream>
#include <vector>
#include <string>
#include <stack>

using namespace std;

class Solution {
public:
    // ["0:start:0", "1:start:2", "1:end:5", "0:end:6"]
    // ["0:start:0", "1:start:2", "1:end:5", "0:end:6", "0:start:7","2:start:8", "2:end:9","0:end:12"]
    // ["0:start:0", "1:start:2", "1:end:5", "0:start:7","2:start:8", "2:end:9","0:end:12"]
    // 分析：每次start的时候，需要判断当前栈顶是否存在正在执行的函数， 如果存在，需要加上出当前这个字符串和上一个字符串之间的执行时间
    // 每次end入栈的时候，需要判断当前end是否对应上一个字符串，是，则直接计算时间， 否，则计算当前字符串和上一个字符串之间差值，加入到栈顶执行时间
    vector<int> exclusiveTime1(int n, vector <string> &logs) {
        stack <pair<int, int>> st; // {idx, 开始运行的时间}
        vector<int> res(n, 0);
        for (auto &log : logs) {
            char type[10];
            int idx, timestamp;
            sscanf(log.c_str(), "%d:%[^:]:%d", &idx, type, &timestamp);
			//    vector <string> nums = {"0:start:0", "0:start:2", "0:end:5", "1:start:7", "1:end:7", "0:end:8"};
			//    vector <string> nums = {"0:start:0","1:start:2","1:end:5","0:end:6"}; // 正确的应该是3,4
            if (type[0] == 's') {
                if (!st.empty()) {
                    res[st.top().first] += timestamp - st.top().second;
                    st.top().second = timestamp;
                }
                st.emplace(idx, timestamp);
            } else {
                auto t = st.top();
                st.pop();
                res[t.first] += timestamp - t.second + 1;
                if (!st.empty()) {
                    st.top().second = timestamp + 1;
                }
            }
        }
        return res;
    }

    vector<int> exclusiveTime(int n, vector <string> &logs) {
        int len = logs.size();
		vector<int> res(n, 0);
        vector<pair<int, int>>st;
		for(int i = 0; i < len; i++){
			auto cur = getIndexPos(logs[i]);
			if(logs[i].find_first_of("s") != string::npos){
				if(!st.empty()){
					auto top = st.back();
					res[top.first] += cur[1] - top.second;
					st.back().second = cur[1];
				}
				st.push_back({cur[0], cur[1]});
			}else{
				auto top = st.back();
				st.pop_back();
				res[cur[0]] += cur[1] - top.second + 1;
				if(!st.empty()){
					st.back().second = cur[1] + 1;
				}
			}
		}
        return res;
    }

    vector<int> getIndexPos(const string &s) {
        int index = stoi(s.substr(0, s.find_first_of(":")));
        int pos = stoi(s.substr(s.find_last_of(":") + 1));
        return {index, pos};
    }
};

int main() {
    Solution so;
	vector <string> nums = {"0:start:0","1:start:2","1:end:5","0:end:6"};
    auto a = so.exclusiveTime(2, nums);
    for (auto i : a) {
        cout << i << ",";
    }
    cout << endl;
    return 0;
}